package com.sangu.dianxiu.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.sangu.dianxiu.BaseApp;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.config.Constants;

import java.util.List;
//地址选择
public class MapSelectActivity extends BaseActivity implements BDLocationListener{
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private LocationClient locationClient;
    private BitmapDescriptor bitmap;
    private String address= "";
    private View popView;
    private boolean isFirst=true;
    private boolean isManual=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_select);
        // 在使用SDK各组件之前初始化context信息，传入ApplicationContext
        // 注意该方法要再setContentView方法之前实现
        // 获取地图控件引用
        initMap();
        initLocation();
    }
    private void initMap() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        ((Button) findViewById(R.id.request)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocation();
            }
        });
        mBaiduMap = mMapView.getMap();
        //设置是否显示比例尺控件
        mMapView.showScaleControl(true);
        //设置是否显示缩放控件
        mMapView.showZoomControls(true);
        // 不能删除百度地图LoGo
       // mMapView.removeViewAt(1);
        // 设置marker图标
        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.marker);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public boolean onMapPoiClick(MapPoi arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            //此方法就是点击地图监听
            @Override
            public void onMapClick(LatLng latLng) {
                //获取经纬度
                double latitude = latLng.latitude;
                double longitude = latLng.longitude;
                Toast.makeText(MapSelectActivity.this, "latitude=" + latitude + "longitude=" + longitude, Toast.LENGTH_SHORT).show();
                //先清除图层
                mBaiduMap.clear();
                // 定义Maker坐标点
                LatLng point = new LatLng(latitude, longitude);
                // 构建MarkerOption，用于在地图上添加Marker
                MarkerOptions options = new MarkerOptions().position(point)
                        .icon(bitmap);
                // 在地图上添加Marker，并显示
                mBaiduMap.addOverlay(options);
                //实例化一个地理编码查询对象
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                op.location(latLng);
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        address = arg0.getAddress();
                        Toast.makeText(MapSelectActivity.this, address, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
            }
        });
    }
    private void initLocation()
    {
        locationClient=new LocationClient(this,getLocOption());
        locationClient.registerLocationListener(this);
        locationClient.start();
    }
    public void requestLocation() {
        isManual=true;
        if(locationClient != null && locationClient.isStarted()){

            Toast.makeText(this, "正在定位...", Toast.LENGTH_SHORT).show();
            locationClient.requestLocation();
        }
    }
    private LocationClientOption getLocOption() {
        LocationClientOption option=new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd0911");
        option.setScanSpan(3 * 1000);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setIsNeedLocationPoiList(true);
        return option;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    /**
     * 接收异步返回的定位结果，参数是BDLocation类型参数
     */
    @Override
    public void onReceiveLocation(BDLocation location) {
        Intent intent=new Intent();
        intent.putExtra("locAddress",location.getAddrStr());
        intent.putExtra("lat",location.getLatitude());
        intent.putExtra("lon",location.getLongitude());
        setResult(Constants.REQUEST_CODE_MAP_SELECT,intent);
        this.finish();
        StringBuffer sb = new StringBuffer(256);
        List<Poi> list = location.getPoiList();// POI信息
        if (list != null) {
            sb.append("\npoilist size = : ");
            sb.append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ");
                sb.append(p.getId() + " " + p.getName() + " " +p.describeContents());
            }
        }

        Toast.makeText(MapSelectActivity.this,sb,Toast.LENGTH_LONG).show();
        popView = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);
        TextView popText = ((TextView)popView.findViewById(R.id.tv_pop_layout_name));
        popText.setText("[我的位置]\n" + location.getAddrStr());
        if(isFirst||isManual)
        {
            isFirst=false;
            isManual=false;
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(new LatLng(location.getLatitude(),location.getLongitude()))
                    .zoom(16)
                    .build();
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //以动画的方式改变地图状态，过渡会自然一些
            mBaiduMap.animateMapStatus(mMapStatusUpdate);
            InfoWindow infoWindow = new InfoWindow(popView, new LatLng(location.getLatitude(),location.getLongitude()), -10);
            mBaiduMap.showInfoWindow(infoWindow);           //显示信息窗
        }

    }

}
